package myauctioneer.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import myauctioneer.App;
import myauctioneer.service.ArticleService;

/**
 * Basis Servlet Klasse, von der alle andere Kontrollerklassen ableiten sollen.
 */
public class DefaultServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Inizialisierungs methode.
	 * Hier wird auch App inizialisiert, falls nötig.
	 */
	public void init() throws ServletException {
		if (App.getBaseDir() == null) {
			try {
				/**
				 * Initialize the application.
				 */
				App.init(this.getServletContext().getRealPath("/"), // baseDir
						this.getServletContext().getContextPath() // baseUrl
				);
			} catch (Exception e) {
				throw new ServletException(e.toString(), e);
			}
		}
	}

	/**
	 * Parse action name from request.
	 * 
	 * @param request
	 *            The servlet request currentry processing
	 */
	protected void parseRequest(HttpServletRequest request) {
		String[] parts = request.getPathInfo() == null ? new String[0]
				: request.getPathInfo().split("/");

		String action = "";

		/**
		 * Check action name
		 */
		if (parts.length > 1)
			action = parts[1];

		if (action.isEmpty())
			action = "index";

		request.setAttribute("action", action);
	}

	/**
	 * Respond to a request for the content produced by this servlet.
	 * Weiterleitet die Anfragen zu den zugehörigen Kontrollmethoden (Actions).
	 * 
	 * @param request
	 *            The servlet request we are processing
	 * @param response
	 *            The servlet response we are producing
	 * 
	 * @exception IOException
	 *                if an input/output error occurs
	 * @exception ServletException
	 *                if a servlet error occurs
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		response.setContentType("text/html; charset=utf-8");

		this.parseRequest(request);

		java.lang.reflect.Method actionMethod = null;
		String action = (String) request.getAttribute("action");

		try {
			actionMethod = this.getClass().getDeclaredMethod(action + "Action",
					HttpServletRequest.class, HttpServletResponse.class);
		} catch (Exception e) {
			this.notFoundAction(request, response);
		}

		if (actionMethod != null) {
			try {
				actionMethod.invoke(this, request, response);
			} catch (Exception e) {
				throw new ServletException(e.toString(), e);
			}
		}

		String template = (String) request.getAttribute("template");

		App.getLogger().info("Template: " + template);

		if (template != null)
			request.getRequestDispatcher("/template/" + template).forward(
					request, response);
	}

	/**
	 * Not found (404) action method.
	 */
	public void notFoundAction(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		response.setStatus(404);
		request.setAttribute("template", "notFound.jsp");
	}

	/**
	 * Index action method.
	 */
	public void indexAction(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException
	{
		ArticleService articleService = new ArticleService();
		java.util.HashMap<String,String> q = new java.util.HashMap<String,String>();

		q.put("query", request.getParameter("search_field"));
		q.put("category", request.getParameter("search_category"));

		request.setAttribute("aAL", articleService.query(q));
		request.setAttribute("template", "index.jsp");
	}
}
